import ROBOT_AVATAR from '@/assets/image/avatar_robo.png';
import topdisplay from '@/assets/image/topdisplay.png';
import { getAllWriting, update_display_order } from '@/services/ant-design-pro/docList';
import { message, Modal, Tabs, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import './index.less';
// 图片
import DocItem from './com/DocItem';

// 有历史记录组件
const AllArticle: React.FC = () => {
  const [tabName, setTabName] = useState(null);
  const [documentType, setDocumentType] = useState('');
  const [docNo, setDocNo] = useState(null); // 选中的文章no
  const [currentArticle, setCurrentArticle] = useState(null); // 选中的文章
  const [defaultActiveKey, setDefaultActiveKey] = useState(''); // 默认激活的tab
  const [defaultActiveIndex, setDefaultActiveIndex] = useState(0); // 默认激活的tab的索引
  // const [loading, setLoading] = useState(false); // 加载中
  const [documentList, setDocumentList] = useState<any[]>([]); // 选中文档列表
  const [otherList, setOtherList] = useState<any[]>([]); // 未选中文档列表
  const [tabItems, setTabItems] = useState<any[]>([]); //标签名称
  const [allData, setAllData] = useState<any[]>([]); //所有数据

  // 切换tab
  const onChange = (e: any) => {
    allData.forEach((v: any, index: number) => {
      if (v.writing_struct_id === e) {
        setTabName(v.writing_struct_name);
        setDocumentList(v.documents);
        setOtherList(v.other_documents);
        setDefaultActiveKey(e);
        setDefaultActiveIndex(index);
      }
    });
  };

  const queryValue = history.location.search;

  // 加载数据
  const loadMoreData = async () => {
    if (!queryValue) {
      message.open({
        type: 'error',
        content: '参数id不能为空',
      });
      return;
    }
    const sId = queryValue.split('?')[1].split('=')[1];
    const params = {
      id: sId,
    };
    const res = await getAllWriting(params);
    if (res.code === 0) {
      const tabs = res.data.documents.map((v: any) => {
        let total = v?.documents?.length + v?.other_documents?.length;
        return {
          key: v.writing_struct_id,
          label: v.writing_struct_name + '  ' + total,
        };
      });
      setAllData(res.data.documents);
      setTabItems(tabs);
      setTabName(
        res.data.documents[defaultActiveIndex].writing_struct_name
          ? res.data.documents[defaultActiveIndex].writing_struct_name
          : '-',
      ); // 行文结构名称
      setDocumentList(res.data.documents[defaultActiveIndex].documents);
      setOtherList(res.data.documents[defaultActiveIndex].other_documents);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };

  // 置顶
  const updateDisplayOrder = async (params: any) => {
    const res = await update_display_order(params);
    if (res.code === 0) {
      // 置顶成功
      message.open({
        type: 'success',
        content: '外置顶成功',
      });
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };

  //下拉点击事件-置顶
  const showTopClick = (item: any) => {
    const uuids: string[] = [item.document_uuid];
    if (documentList.length > 1) {
      for (let index = 0; index < documentList.length - 1; index++) {
        const document = documentList[index];
        uuids.push(document.document_uuid);
      }
    }

    const params = {
      writing_session_id: item.writing_session_id,
      writing_structure_id: item.writing_structure_id,
      selected_document_uuids: uuids,
    };
    if (documentType === 'topDoc') {
      setDocumentType('otherDoc');
    } else if (documentType === 'otherDoc') {
      setDocumentType('topDoc');
    }
    let index = 0; // 置换的索引
    otherList.forEach((v: any, i: number) => {
      if (v.document_uuid === item.document_uuid) {
        index = i;
      }
    });
    const dl = [...documentList]; //这里是重点，直接拷贝一份出来，
    const ol = [...otherList]; //这里是重点，直接拷贝一份出来，
    // 底下删一个
    ol.splice(index, 1);
    // 顶部插入一个
    dl.unshift(item);
    if (dl.length > 2) {
      // 长度大于3，底部插入一个 顶部删除最后一个
      let lastIndex = dl.length - 1;
      ol.unshift(dl[lastIndex]);
      dl.pop();
    }
    setOtherList(ol);
    setDocumentList(dl);
    updateDisplayOrder(params);
  };

  //page变动时触发请求
  useEffect(() => {
    loadMoreData();
  }, []);

  //示例modal
  const [isDemoOpen, setIsDemoOpen] = useState(false);
  const [currentDemo, setCurrentDemo] = useState<any[]>([]); //当前示例
  //关闭示例
  const demoModalCancel = () => {
    setIsDemoOpen(false);
  };
  const articleEleRef = useRef<any>(null); //文章外部的容器 用于滚动条重置
  const articleElement = useRef<any>(null);
  //显示示例
  const showDemo = (event: any, item: any, type: any) => {
    event.stopPropagation(); //阻止冒泡
    setDocumentType(type);
    setDocNo(item.doc_no);
    setCurrentArticle(item);
    setIsDemoOpen(true);
    //将\n替换成p标签包裹文字
    item.example_title = item.current_document_version.title;
    item.article = item.current_document_version.system_output
      .split('\n')
      .map((paragraph: any) => `<p>${paragraph}</p>`)
      .join('');
    articleElement.current = React.createElement('div', {
      dangerouslySetInnerHTML: { __html: item.article },
    });
    setCurrentDemo(item);
    //冒泡阻止点击事件
    setTimeout(() => {
      if (articleEleRef.current) {
        articleEleRef.current.scrollTop = 0;
      }
    }, 200);
  };

  return (
    <div className="page-container">
      <div className="statefulComponent">
        <Tabs defaultActiveKey={defaultActiveKey} items={tabItems} onChange={(e) => onChange(e)} />
        <div className="docTypeTitleBox">
          展示文章
          <span className="docTypeTitleNum">{documentList.length}</span>
        </div>
        <div className="doc-box">
          <div className="docTypeListBox">
            {documentList.map((item: any) => {
              return (
                <DocItem
                  key={item.document_id}
                  item={item}
                  showDemo={showDemo}
                  tabName={tabName}
                  type="topDoc"
                  showTopClick={showTopClick}
                />
              );
            })}
          </div>
        </div>
        <div className="docTypeTitleBox" style={{ marginTop: '20px' }}>
          其他文章
          <span className="docTypeTitleNum">{otherList.length}</span>
          <div className="docTypeTipBox">
            <img className="botAvatar" src={ROBOT_AVATAR} alt="" height={28} width={28} />
            可以点击下方卡片上的「置顶」功能，可以将文章展示在文章生成区域。
          </div>
        </div>
        {otherList.length > 0 && (
          <div className="doc-box other-doc">
            <div className="docTypeListBox">
              {otherList.map((item: any) => {
                return (
                  <DocItem
                    key={item.document_id}
                    item={item}
                    showDemo={showDemo}
                    tabName={tabName}
                    type="otherDoc"
                    showTopClick={showTopClick}
                  />
                );
              })}
            </div>
          </div>
        )}
        {/* <div>{open}</div> */}
        <Modal
          centered
          className="demoModal"
          title={currentDemo.example_title}
          open={isDemoOpen}
          onCancel={demoModalCancel}
          width={650}
          footer={[
            <div className="flex-acen-sb" key="meishayong">
              <div className="flex-aitem-center">
                <div className="rate-circle f-s-14"></div>
                <div className="m-l-10">NO.{docNo}</div>
              </div>
              <div>
                <Tooltip
                  placement="top"
                  title={documentType === 'otherDoc' ? '置顶' : ''}
                  arrow={true}
                  className={`card-more ${documentType === 'otherDoc' ? 'cursor-point' : ''}`}
                >
                  {documentType === 'otherDoc' ? (
                    <div onClick={() => showTopClick(currentArticle)}>
                      <img src={topdisplay} height={15} width={15} />
                    </div>
                  ) : (
                    <div>{/* <img src={outdisplay} height={15} width={15} /> */}</div>
                  )}
                </Tooltip>
              </div>
            </div>,
          ]}
        >
          <div className="articleEleRef" ref={articleEleRef}>
            {articleElement.current}
          </div>
        </Modal>
      </div>
    </div>
  );
};
export default AllArticle;
